// 验证报名数据是否正确写入的云函数
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { registrationId } = event
  
  console.log('开始验证报名数据，registrationId:', registrationId)
  console.log('用户OPENID:', wxContext.OPENID)
  
  // 直接使用openid作为用户标识
  if (!wxContext.OPENID) {
    return {
      success: false,
      message: '用户未登录'
    }
  }
  
  const userOpenid = wxContext.OPENID
  console.log('用户OPENID:', userOpenid)
  
  try {
    const results = {}
    
    // 1. 检查报名记录
    const registrationResult = await db.collection('activity_registrations').doc(registrationId).get()
    if (registrationResult.data) {
      results.registration = {
        exists: true,
        data: registrationResult.data
      }
      console.log('✓ 报名记录存在')
    } else {
      results.registration = {
        exists: false,
        message: '报名记录不存在'
      }
      console.log('✗ 报名记录不存在')
    }
    
    // 2. 检查活动成员记录
    const membersResult = await db.collection('activity_members').where({
      registrationId: registrationId
    }).get()
    results.members = {
      count: membersResult.data.length,
      data: membersResult.data
    }
    console.log(`✓ 找到${membersResult.data.length}个活动成员记录`)
    
    // 3. 检查用户信息和余额
    const userResult = await db.collection('users').where({
      _openid: wxContext.OPENID
    }).get()
    if (userResult.data.length > 0) {
      results.user = {
        exists: true,
        balance: userResult.data[0].balance,
        data: userResult.data[0]
      }
      console.log('✓ 用户信息存在，当前余额:', userResult.data[0].balance)
    } else {
      results.user = {
        exists: false,
        message: '用户信息不存在'
      }
      console.log('✗ 用户信息不存在')
    }
    
    // 4. 检查用户活动中继表
    const relayResult = await db.collection('user_activity_relay').where({
      userId: userOpenid
    }).get()
    if (relayResult.data.length > 0) {
      const activityRecords = relayResult.data[0].activityRecords || []
      const targetRecord = activityRecords.find(record => 
        record.activityId === results.registration?.data?.activityId
      )
      results.relay = {
        exists: true,
        hasTargetRecord: !!targetRecord,
        totalRecords: activityRecords.length,
        targetRecord: targetRecord,
        data: relayResult.data[0]
      }
      console.log('✓ 用户活动中继表存在，包含目标记录:', !!targetRecord)
    } else {
      results.relay = {
        exists: false,
        message: '用户活动中继表记录不存在'
      }
      console.log('✗ 用户活动中继表记录不存在')
    }
    
    // 5. 生成验证报告
    // 5. 生成验证报告
    const report = {
      registrationId: registrationId,
      userId: userOpenid,
      openid: wxContext.OPENID,
      timestamp: new Date().toISOString(),
      summary: {
        registrationExists: results.registration?.exists || false,
        membersCount: results.members?.count || 0,
        userExists: results.user?.exists || false,
        userBalance: results.user?.balance || 0,
        relayExists: results.relay?.exists || false,
        relayHasRecord: results.relay?.hasTargetRecord || false
      },
      details: results
    }
    
    console.log('验证报告:', JSON.stringify(report.summary, null, 2))
    
    return {
      success: true,
      message: '验证完成',
      data: report
    }
    
  } catch (error) {
    console.error('验证失败:', error)
    return {
      success: false,
      message: '验证失败: ' + error.message,
      error: error
    }
  }
}